﻿using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using PineLake.Drmwe.SystemConfig;
using PineLake.Drmwe.Tickets.Jwt.Model;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace PineLake.Drmwe.Tickets.Jwt
{
    /// <summary>
    /// JWT Token
    /// </summary>
    public class JWTToken : IJWTToken
    {
        /// <summary>
        /// 生成JWT 令牌
        /// </summary>
        /// <param name="Param">令牌参数</param>
        /// <returns></returns>
        public string CreateToken(TokenParam Param)
        {
            var Claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, Param.TicketId), //可以通过this.User.Identity.Name访问到第二个参数的值
                    new Claim(ClaimTypes.Role,Param.Group),     //角色权限分组
                    new Claim(ClaimTypes.Version,Param.Version), //版本
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),//JWT ID
                };
            var Key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.AuthorKey));//密钥
            var Token = new JwtSecurityToken(
                issuer: AppSettings.AuthorIssuer,//颁发Token(授权)
                audience: AppSettings.AuthorAudience,//token接收(授权)
                claims: Claims,
                notBefore: Param.DateTimes,
                expires: Param.DateTimes.AddDays(Param.ExpiresTimeByDay == 0 ? int.Parse(AppSettings.AuthorExpires) : Param.ExpiresTimeByDay),
                signingCredentials: new SigningCredentials(Key, SecurityAlgorithms.HmacSha256)
            );
            var JwtToken = new JwtSecurityTokenHandler().WriteToken(Token);
            JwtToken = "Bearer " + JwtToken;
            return JwtToken;
        }
    }
}
